from socket import *
import os, sys
import signal

# 创建监听套接字

HOST = '0.0.0.0'
PORT = 8888
ADDR = (HOST, PORT)

sockfd = socket(AF_INET, SOCK_STREAM)
# 设置端口立即启动
sockfd.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
sockfd.bind(ADDR)
sockfd.listen(50)

# 僵尸进程处理
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
print('Listen the port 8888...')


def handle(c):
    print('客户端：', c.getpeername())
    while True:
        data = c.recv(1024)
        # 客户端关掉进程会收到空信息
        if not data:
            break
        print(data.decode())
        c.send(b'OK')
    c.close()


# 循环等待客户端链接
while True:
    try:
        c, addr = sockfd.accept()
    except KeyboardInterrupt:
        sys.exit('服务器退出')
    except Exception as e:
        print(e)
        continue

    # 创建子进程处理客户端请求
    pid = os.fork()
    if pid == 0:
        # 子进程不需要sockfd
        sockfd.close()
        # 具体处理客户端请求
        handle(c)
        os._exit(0)
    else:
        # 父进程不需要c
        c.close()
